<template>
  <div>
    <!-- 导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>仓库管理</el-breadcrumb-item>
      <el-breadcrumb-item>仓库商品列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <!-- 搜索区域 -->
      <el-row :gutter="25">
        <el-col :span="10">
          <!-- 搜索框 -->
          <el-input 
            placeholder="请输入搜索内容" 
            v-model="queryInfo.query" 
            clearable
            @clear="getWarehouseProducts"
          >
            <template #append>
              <el-button 
                icon="el-icon-search" 
                @click="filterProductsByName"
              ></el-button>
            </template>
          </el-input>
        </el-col>
      </el-row>
      <!-- 选择仓库地址 -->
      <el-row :gutter="20" style="margin-bottom: 20px;">
        <el-col :span="6">
          <el-select v-model="selectedVarietyType" placeholder="请选择种类" @change="getWarehouseProducts">
            <el-option label="无" value=""></el-option>
            <el-option
              v-for="type in varietyTypes"
              :key="type"
              :label="type"
              :value="type">
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-select v-model="selectedLocation" placeholder="请选择仓库地址" @change="getWarehouseProducts">
            <el-option
              v-for="location in warehouseLocations"
              :key="location"
              :label="location"
              :value="location">
            </el-option>
          </el-select>
        </el-col>
      </el-row>

      <!-- 商品列表 -->
      <el-table :data="warehouseProducts" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="商品名称" prop="productName"></el-table-column>
        <el-table-column label="货量（吨）" prop="quantity"></el-table-column>

        <!-- 操作列 -->
      <el-table-column label="操作">
        <template v-slot:default="scope">
          <el-button 
            size="mini" 
            type="success" 
            icon="el-icon-truck" 
            @click="handleOutbound(scope.row)"
            plain
          >
            出库
          </el-button>
        </template>
      </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div style="margin-top: 20px;">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pageNum"
          :page-sizes="[5, 10, 20]"
          :page-size="queryInfo.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      warehouseLocations: [],
      selectedLocation: '',
      warehouseProducts: [],     // 当前显示的数据
      originalProducts: [],      // 原始完整数据
      total: 0,
      queryInfo: {
        pageNum: 1,
        pageSize: 10
      },
      varietyTypes: [],          // 所有种类列表
      selectedVarietyType: ''    // 默认不选中任何种类
    };
  },
  created() {
    this.fetchVarietyTypes();     // 再获取种类
    this.getWarehouseLocations(); // 先获取仓库地址
    this.getWarehouseProducts();
  },
  methods: {
    // ✅ 根据地址获取商品（带分页）
    async getWarehouseProducts() {
      const params = {
        pageNum: this.queryInfo.pageNum,
        pageSize: this.queryInfo.pageSize
      };

      let location = this.selectedLocation;

      if (!location && this.warehouseLocations.length > 0) {
        location = this.warehouseLocations[0]; // 默认使用第一个地址
      }

      if (location) {
        params.location = location;
      }

      params.varietyType = this.selectedVarietyType || '';

      try {
        const response = await axios.post('/warehouse/products', params);
        console.log('接口返回数据:', response.data);

        this.warehouseProducts = response.data.list || [];
        this.total = response.data.total || 0;

      } catch (error) {
        console.error('获取仓库商品失败:', error);
        this.$message.error('获取仓库商品失败，请稍后再试');
      }
    },

    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize;
      this.getWarehouseProducts();
    },
    handleCurrentChange(newPage) {
      this.queryInfo.pageNum = newPage;
      this.getWarehouseProducts();
    },

    // ✅ 出库操作
    async handleOutbound(product) {
      try {
        const productInfoHTML = `
          <div style="text-align: left; margin-bottom: 15px;">
            <p><strong>商品名称：</strong>${product.productName}</p>
            <p><strong>当前库存：</strong>${product.quantity} 吨</p>
          </div>
        `;

        const { value: quantity } = await this.$prompt(
          productInfoHTML + '请输入出库数量（吨）',
          '出库操作',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            inputPattern: /^[1-9]\d*$/,
            inputErrorMessage: '请输入大于0的整数',
            inputType: 'number',
            inputPlaceholder: '请输入出库数量',
            dangerouslyUseHTMLString: true
          }
        ).catch(() => {
          this.$message.info('已取消');
          return { value: null };
        });

        if (quantity === null) return;

        if (parseInt(quantity) > product.quantity) {
          this.$message.error('出库数量不能超过当前库存');
          return;
        }

        const employeeUsername = localStorage.getItem('employeeId');

        if (!employeeUsername) {
          this.$message.error('未找到员工信息，请重新登录');
          return;
        }

        const outData = {
          productName: product.productName,
          quantity: parseInt(quantity),
          location: this.selectedLocation,
          employeeUsername: employeeUsername
        };

        const response = await axios.post('/inventory/out', outData);

        if (response.status === 200) {
          this.$message.success('出库成功');
          this.getWarehouseProducts();
        } else {
          this.$message.error('出库失败，请重试');
        }
      } catch (error) {
        console.error('出库失败:', error);
        if (error.response) {
          this.$message.error(`出库失败: ${error.response.data.message || '未知错误'}`);
        } else {
          this.$message.error('网络错误，请稍后再试');
        }
      }
    },

    // ✅ 搜索方法
    filterProductsByName() {
      if (!this.queryInfo.query) {
        this.warehouseProducts = [...this.originalProducts];
        this.total = this.originalProducts.length;
        return;
      }

      const filtered = this.originalProducts.filter(product =>
        product.productName.includes(this.queryInfo.query)
      );

      this.warehouseProducts = filtered;
      this.total = filtered.length;
    },
    async fetchVarietyTypes() {
      try {
        const response = await axios.get('/agricultural/variety-types');
        console.log('接口返回种类:', response.data);

        this.varietyTypes = response.data.map(item => item.varietyType);
      } catch (error) {
        console.error('获取种类失败:', error);
        this.$message.error('无法加载种类，请检查网络或稍后再试');
      }
    },
    async getWarehouseLocations() {
      try {
        const response = await axios.get('/warehouse/locations');
        this.warehouseLocations = response.data.data || [];
        
        if (this.warehouseLocations.length > 0) {
          this.selectedLocation = this.warehouseLocations[0]; // 默认选中第一个地址
        }
      } catch (error) {
        console.error('获取仓库地址失败:', error);
        this.$message.error('获取仓库地址失败，请稍后再试');
      }
    }
  }
};
</script>

<style scoped>
.el-card {
  margin-top: 20px;
}
</style>